package champPackage;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.*;
import java.sql.Date;
import java.util.*;

import javax.servlet.RequestDispatcher;

public class DBManager {
	static String server = "localhost";
	static String password = "malibu";
	static String account = "root";
	static String database = "mysql";
	private static  Connection con;
	private static Connection con1;
	private static DBManager db;
	 
	public static DBManager getInstance(){
		if(db==null) db = new DBManager();
		return db;
	}
	 
	private DBManager(){
		try {
			 Class.forName("com.mysql.jdbc.Driver");
			 con = DriverManager.getConnection("jdbc:mysql://" + server, account, password);
			 con1 = DriverManager.getConnection("jdbc:mysql://" + server, account, password);
		}
		 
		//es eqseption rom ar moxdes conector jar chaagdet web-inf_is lib foldershic
		catch (ClassNotFoundException e) {
			  System.out.println("Class not found Exception!!!!!");
			  e.printStackTrace();
		}
		catch (SQLException e) {
			 System.out.println("SQL Exception");
			 e.printStackTrace();
		}
	}
	
	
public Iterator getTeamPlayers(Team t,Championship ch) throws SQLException{		
		ArrayList<String>list= new ArrayList<String>();
		Statement stmt = con.createStatement();
		stmt.executeQuery("use " + database);
		int teamId=t.getId();
		//int championshipId=ch.getId();
		ResultSet rs = stmt.executeQuery("Select player_id from teamPlayers where team_id="+teamId+" and championship_id=1;");	
		System.out.println("while-mde");
		while(rs.next()){
			String playerID=rs.getString(1);
			int playerId= Integer.parseInt(playerID);
			Statement stmt1 = con1.createStatement();
			stmt1.executeQuery("use "+database);
			ResultSet rs2 = stmt1.executeQuery("Select * from players where player_id="+playerId+";");
			//System.out.println(rs2==null);
			if(rs2.next());
			String playerName=rs2.getString("player_name");
			System.out.println(playerName+" "+rs2==null);
			Date dabadebisTarigi=Date.valueOf(rs2.getString("date_of_birth"));
			System.out.println(playerName+" "+dabadebisTarigi);
			list.add(playerName);
		}
		return list.iterator();		
	}


	/**
	 * returns championship Id for new championship
	 * @return Id of new championship
	 * @throws SQLException
	 */
	
	public int getNewChampionshipId() throws SQLException{
		Statement stmt = con.createStatement();
		stmt.executeQuery("use " + database);
		ResultSet rs=stmt.executeQuery("SELECT COUNT(championship_id) FROM championshipInfo");
		rs.next();
		String result=rs.getString("count(championship_id)");
		
		return Integer.parseInt(result)+1;
		
	}

	/**
	 * creates new championship. adds new championship into userChampionships Table
	 * @param id championship ID
	 * @param userName
	 * @throws SQLException
	 */
	public void addNewChampionship(int id, int userName) throws SQLException{
		Statement stmt = con.createStatement();
		stmt.executeQuery("use " + database);
		stmt.executeUpdate("insert into userChampionships values ('"+userName+"', '"+id+"');");
	}
	
	/**
	 * @author Tengo
	 * this boolean checks whether the userName and password matches the one in dataBase
	 * @throws NoSuchAlgorithmException 
	 * @throws SQLException 
	 * 
	 */
	public boolean isCorrectUser(String userName, String password) throws NoSuchAlgorithmException, SQLException{
		Statement stmt = con.createStatement();
		stmt.executeQuery("use " + database);
		ResultSet rs = stmt.executeQuery("Select user_password from userInfo where user_name="+userName+";");
		if(!rs.first())return false;
		String hashValue=rs.getString(1);
		MessageDigest digest=  MessageDigest.getInstance("SHA");
		digest.update(password.getBytes());
		byte[]result=digest.digest();
		String kodi=hexToString(result);
		if(hashValue.equals(kodi))return true;		
		return false;
	}
	

/**
	public static void main(String[] args) throws SQLException {
		DBManager db = DBManager.getInstance();
//		Team t = new Team("Lasha");
//		Championship ch = new Championship(null);
//		Iterator<String> it = db.getTeamPlayers(t, ch);
//		while(it.hasNext()){
//			String s = it.next();
//			System.out.println(s);
//		}
		System.out.println(db.getNewChampionshipId());
		db.addNewChampionship(48, 1);
	}
*/
	
	private void addUserInfoToTheDatabase(String user, String password, String email, String type){
		Statement stmt = con.createStatement();
		stmt.executeQuery("use " + database);
		MessageDigest digest = MessageDigest.getInstance("SHA");
		digest.update(password.getBytes());
		byte[]result=digest.digest();
		String kodi=hexToString(result);
		stmt.executeUpdate("insert into userInfo values ("+type+", "+userName+", "+kodi+","+email");");
	}
	
	/*
	 Given a byte[] array, produces a hex String,
	 such as "234a6f". with 2 chars for each byte in the array.
	 (provided code)
	*/
	public static String hexToString(byte[] bytes) {
		StringBuffer buff = new StringBuffer();
		for (int i=0; i<bytes.length; i++) {
			int val = bytes[i];
			val = val & 0xff;  // remove higher bits, sign
			if (val<16) buff.append('0'); // leading 0
			buff.append(Integer.toString(val, 16));
		}
		return buff.toString();
	}
}
